package message;

import entity.ChessUser;
import message.server.ServerLoggedMessage;
import message.server.ServerLoginFailMessage;
import message.server.ServerLoginSucMessage;
import message.server.ServerRoomListMessage;
import message.server.ServerUserListMessage;
import socket.ChessServer;

/**
 * 登录报文.
 *
 * @author 张紘溢
 */
public class LoginMessage extends BaseMessage {
    private String username;

    public LoginMessage(String username) {
        this.username = username;
    }

    @Override
    public void sendToServer() {
        if (!username.isEmpty()) {
            //指定接收者
            this.accepter = this.sender;
            //生成response报文
            ChessUser chessUser = ChessServer.getInstance().getChessUserService().findUser(username);
            if (!ChessServer.getInstance().logged(chessUser)) {
                message.server.ServerLoggedMessage serverLoggedMessage = new ServerLoggedMessage();
                ChessServer.getInstance().sendMsgToClient(serverLoggedMessage, this.accepter.getClient());
                return;
            }
            message.server.ServerLoginSucMessage serverLoginSucMessage = new ServerLoginSucMessage(chessUser);
            //服务器发送报文给指定客户
            System.out.println(serverLoginSucMessage);
            ChessServer.getInstance().sendMsgToClient(serverLoginSucMessage, this.accepter.getClient());
            //将客户端的用户名与所分配到的线程进行绑定
            //有username查询dao得到User对象user

            ChessServer.getInstance().bindUsername(chessUser, accepter.getClient());
            //向所有客户端发送在线用户列表
            message.server.ServerUserListMessage serverUserListMessage = new ServerUserListMessage(ChessServer.getInstance().getUserList());
            ChessServer.getInstance().sendMsgToAll(serverUserListMessage);
            //服务器向登录的客户端发送房间列表报文
            message.server.ServerRoomListMessage serverRoomListMessage = new ServerRoomListMessage(ChessServer.getInstance().getRooms());
            ChessServer.getInstance().sendMsgToClient(serverRoomListMessage, this.accepter.getClient());


        } else {
            message.server.ServerLoginFailMessage serverLoginFailMessage = new ServerLoginFailMessage();
            ChessServer.getInstance().sendMsgToClient(serverLoginFailMessage, this.accepter.getClient());
        }
    }

    @Override
    public void selfExecute() {

    }
}
